package com.lvkedu.dataforward.dao;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class ForwardDao {

    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    JdbcTemplate jdbcTemplate;

    /**
     * 这里以表raw_data为例，定时传入参数，每10分钟一次
     *
     * @param jsonStr
     */
    public void saveRawSensorData(String jsonStr) {
        String sql = "insert into raw_data(device_id, sensor_id, sensor_name, value, alarm_min, alarm_max, alarm_state, report_time)" +
                " VALUES (?,?,?,?,?,?,?,?)";
        JSONArray jsonArray = JSONArray.parseArray(jsonStr);
        if (jsonArray == null || jsonArray.size() == 0) return;
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            String reportTime = object.getString("time");
            String deviceId = object.getString("deviceId");
            JSONArray sensors = object.getJSONArray("sensors");//获取的端口以json数组记录
            if (sensors == null || sensors.size() == 0) continue;
            //分成json对象
            for (int j = 0; j < sensors.size(); j++) {
                JSONObject sensor = sensors.getJSONObject(j);
                String sensorId = sensor.getString("sensorId");
                String sensorName = sensor.getString("sensorName");
                String[] sensorScope = sensor.getString("sensorScope").split("_");  //设置的上下限
                float alarmMin = Float.parseFloat(sensorScope[0]);
                float alarmMax = Float.parseFloat(sensorScope[1]);
                int alarmState = 0;
                float value = 0;
                value = sensor.getFloat("sensorVal");
                if (value <= alarmMin || value >= alarmMax) {
                    alarmState = 1;
                }


                int count = jdbcTemplate.update(sql, deviceId, sensorId, sensorName, value, alarmMin, alarmMax, alarmState, reportTime);
                if (count > 0) {
                    logger.info("写入数据库成功...");
                }
            }
        }
    }
}
